package com.gxp.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.support.RequestContextUtils;


@Controller
public class UploadController {
	
	@RequestMapping(value="/admin/game/upload",method=RequestMethod.POST)
	public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws IOException {	
		
		response.setContentType("text/html; charset=utf-8");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		MultipartFile myfile = multipartRequest.getFile("inputfile");
		
//		Map<String,String> resultMap = new HashMap<String,String>();
//		resultMap.put("ERROR", "");
//		resultMap.put("PIC_URL", "");
//		resultMap.put("PIC_NAME", "");
		
		final String[] allowtype = new String[] { ".JPG", ".JPEG", ".GIF",  
				".BMP", ".PNG", ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
		
		String filename = myfile.getOriginalFilename();  
		String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
		boolean typeok = false;
		
		ApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request);
		for (String type : allowtype) {
			if (type.equals(extName)) {
				typeok = true;
				break;
			}
		}
		if (!typeok) {
//			result[0] = fileTypeError;
//			resultMap.put("ERROR", fileTypeError);
			String fileTypeError = ctx.getMessage("msg.upload.type.unvailable", null, RequestContextUtils.getLocale(request));
			responseJson(response, "", fileTypeError);
//			 PrintWriter out = response.getWriter();
//		     out.write("{\"ERROR\":\" " + fileTypeError + "\"}");
//		     out.flush();
//		     out.close();
		     return;
		}
		
		if (myfile.getSize() > 2 * 1024 * 1024) {
//			result[0] = fileSizeError;
//			resultMap.put("ERROR", fileSizeError);
//			PrintWriter out = response.getWriter();
//		    out.write("{\"ERROR\":\" " + fileSizeError + "\"}");
//		    out.flush();
//		    out.close();
			String fileSizeError = ctx.getMessage("msg.upload.size.oversize", null, RequestContextUtils.getLocale(request));
			responseJson(response, "", fileSizeError);
		    return;
		}

        String name = UUID.randomUUID().toString(); 
        
		String realpath = request.getSession().getServletContext().getRealPath("/fileupload/gamelogo/"); 
		String finalName = name + extName;
		String fileurl = realpath + "/" + finalName;
		try {
			myfile.transferTo(new File(fileurl));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
//		String  url = "<img height=\'80\' width=\'200\' src=\'fileupload/gamelogo/" + finalName + "\' /\>";
		responseJson(response, finalName, "");
	}

	private void responseJson(HttpServletResponse response, String finalName, String error) throws IOException {
		//		result[1] = "<img height='80' width='200' src='fileupload/gamelogo/"+ finalName + "' />";
//				resultMap.put("PIC_URL", "<img height='80' width='200' src='fileupload/gamelogo/"+ finalName + "' />");
		//		result[2] = finalName;
//				resultMap.put("PIC_NAME", finalName);
				PrintWriter out = response.getWriter();				
				out.write("{\"ERROR\":\"" + error + "\"," +
						"\"PIC_NAME\":\"" + finalName + "\"}");
			    out.flush();
			    out.close();
	}
	
}
